import axios from 'axios'
import { setLocalForage } from '../utils/localForage'
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL

export function download (book, onSuccess, onError, onProgress) {
  if (!onProgress) {
    onProgress = onError
    onError = null
  }
  return axios.create({
    baseURL: process.env.VUE_APP_EPUB_URL,
    methods: 'get',
    responseType: 'blob',
    timeout: 180 * 1000,
    onDownloadProgress: progressEvent => {
      if (onProgress) onProgress(progressEvent)
    }
  }).get(`${book.categoryText}/${book.fileName}.epub`)
    .then(res => {
      /*
       let fileName = book.fileName + '.epub'
      if (window.navigator.msSaveOrOpenBlob) {
       // 兼容ie11
       var blobObject = new Blob([res.data])
       window.navigator.msSaveOrOpenBlob(blobObject, fileName)
       } else {
       let url = URL.createObjectURL(new Blob([res.data]))
       let a = document.createElement('a')
       document.body.appendChild(a) // 此处增加了将创建的添加到body当中
       a.href = url
       a.download = fileName
       a.target = '_blank'
       a.click()
       a.remove() // 将a标签移除
       }
       */
      const blob = new Blob([res.data])
      setLocalForage(book.fileName, blob, () => {
        if (onSuccess) onSuccess(res)
      }, err => {
        if (onError) onError(err)
      })
    })
}

export function home () {
  return axios.get('/book/home')
}

export function list () {
  return axios.get('/book/list')
}

export function shelf () {
  return axios.get('/book/shelf')
}

export function detail (book) {
  return axios.get(`${process.env.VUE_APP_BOOK_URL}/book/detail`, {
    params: {
      fileName: book.fileName
    }
  })
}

export function flatList() {
  return axios({
    method: 'get',
    url: `${process.env.VUE_APP_BOOK_URL}/book/flat-list`
  })
}
